<template>
  <teleport to="body">
    <div
      class="w-28 p-2.5 fixed z-11 text-slate-600 bg-white shadow-xl border border-sllid border-gray-200"
      :style="styleComputed"
      v-if="visible"
      v-click-outside="closeModal"
    >
      <div
        class="select-none rounded-md p-2.5 cursor-pointer duration-200 hover:bg-sky-100 hover:text-sky-500"
        @click="onEdit('add')"
      >
        新增节点
      </div>
      <div
        class="select-none rounded-md p-2.5 cursor-pointer duration-200 hover:bg-sky-100 hover:text-sky-500"
        @click="onEdit('edit')"
      >
        编辑节点
      </div>
      <div
        class="select-none rounded-md p-2.5 cursor-pointer duration-200 hover:bg-sky-100 hover:text-sky-500"
        @click="onEdit('delete')"
      >
        删除节点
      </div>
    </div>
  </teleport>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";

const visible = ref(false);
const leftPos = ref(0);
const topPos = ref(0);
const node = ref({});

const styleComputed = computed(() => {
  return {
    left: leftPos.value + "px",
    top: topPos.value + "px",
  };
});

const emit = defineEmits(["emitMenu"]);

const onEdit = (command: string) => {
  emit("emitMenu", { command, currentNode: node.value });
};

const showModal = (position: Record<string, any> = { left: 0, top: 0 }) => {
  node.value = position.node;
  leftPos.value = position.left;
  topPos.value = position.top;
  visible.value = true;
};

const closeModal = () => {
  if (visible.value) visible.value = false;
};

defineExpose({
  showModal,
  closeModal,
});
</script>
